#pragma once
#include <iostream>
#include <string>
#include <functional>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <memory>
#include "log.hpp"
#include "InetAddr.hpp"
using namespace LogModule;
using func_t = std::function<std::string(std::string message, InetAddr peer)>;
class UdpServe
{
public:
    UdpServe(uint16_t port, func_t func)
        : _port(port),
          _func(func)
    {
    }
    ~UdpServe() {}
    void Start()
    {
        _isrunning = true;
        while (_isrunning)
        {
            // 1.接受消息
            sockaddr_in peer; // 客户端
            socklen_t len = sizeof(peer);
            char buffer[1024];
            ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (sockaddr *)&peer, &len);
            std::string ret;
            if (n > 0)
            {
                buffer[n] = 0;
                // std::string peer_ip=inet_ntoa(peer.sin_addr);
                // int peer_port=ntohs(peer.sin_port);
                InetAddr client(peer);
                ret = _func(std::string(buffer), client);
                // LOG(LogLevel::INFO)<<"[" << peer_ip << ":" << peer_port<< "]# " << ret;
            }

            // 2.发消息
            // std::string sermes="serve say@"+std::string(buffer);
            // std::cout<<sermes<<std::endl;
            ssize_t n2 = sendto(_sockfd, ret.c_str(), ret.size(), 0, (sockaddr *)&peer, len);
        }
    }
    void Init()
    {
        // 1.创建我们的sockfd
        // 前两个参数就规定了我们用的就是udp
        int n = socket(AF_INET, SOCK_DGRAM, 0);
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "sock error";
            exit(2);
        }
        _sockfd = n;
        LOG(LogLevel::INFO) << "sock success";
        // 创建成功了
        // 进行绑定
        sockaddr_in local;
        // 首先进行清零
        bzero(&local, sizeof(local));
        // 填充字段
        local.sin_family = AF_INET;
        // 把本地转为网络序列
        local.sin_port = htons(_port);
        // 这里就是不显示绑定而是绑定该太机器上任意的ip地址
        local.sin_addr.s_addr = INADDR_ANY;
        int ret = bind(_sockfd, (sockaddr *)&local, sizeof(local));
        if (ret < 0)
        {
            LOG(LogLevel::FATAL) << "bind failsure";
            exit(2);
        }
        LOG(LogLevel::INFO) << "bind success";
    }

private:
    int _sockfd;
    // std::string _ip;//服务器端一台机器上可能有多个ip我们最好的就是不显示绑定我们的ip地址
    uint16_t _port;
    bool _isrunning;
    func_t _func;
};
